package com.qsxc.system.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qsxc.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充处理类
 *
 * @author 
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        fillValue("createdBy", Constants.DEFAULT_CREATED_BY, metaObject);
        fillValue("createdDate", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        fillValue("lastUpdatedBy", Constants.DEFAULT_CREATED_BY, metaObject);
        fillValue("lastUpdatedDate", new Date(), metaObject);
    }

    private void fillValue(String fieldName, Object data, MetaObject metaObject) {
        // 值为空时设置默认值
        Object sidObj = getFieldValByName(fieldName, metaObject);
        if (sidObj == null && metaObject.hasSetter(fieldName)) {
            setFieldValByName(fieldName, data, metaObject);
        }
    }

}
